package com.rams.ls.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;

import net.miginfocom.layout.AC;
import net.miginfocom.layout.CC;
import net.miginfocom.layout.LC;
import net.miginfocom.swing.MigLayout;

import com.rams.ls.Config;
import com.rams.ls.gui.form.BasicForm;
import com.rams.ls.gui.form.FormItems;
import com.rams.ls.gui.form.FormMobs;

public class Application {
	private static BasicForm form;
	private static final JFrame mainForm = new JFrame("jLa2Store");
	private static final JPanel main = new JPanel();
	private static final JToolBar toolbar = new JToolBar();
	
	private static final JButton btnMobs = new JButton("mobs");
	private static final JButton btnResource = new JButton("resources");
	private static final JButton btnWeapon = new JButton("weapons");
	private static final JButton btnArmor = new JButton("armor");
	
	private static Map<String, BasicForm> formsCache = new HashMap<String, BasicForm>();
	
	public void show() {
		mainForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainForm.setMinimumSize(new Dimension(Config.minAppWidth, Config.minAppHeight));
		
		initBtns();
		
		MigLayout ml = new MigLayout(new LC().fill().wrap().debug(Config.debug),
									 new AC().fill(),
									 new AC().fill());
		main.setLayout(ml);
		mainForm.setContentPane(main);
		
		toolbar.setFloatable(false);
		toolbar.add(btnMobs);
		toolbar.add(btnResource);
		toolbar.add(btnWeapon);
		toolbar.add(btnArmor);
		
		main.add(toolbar, new CC().dockNorth());
		
		mainForm.setVisible(true);
		
		mainForm.pack();
	}
	
	private void initBtns() {
		btnMobs.setActionCommand("mobs");
		btnMobs.setText("Mobs");
		btnMobs.addActionListener(new BtnActionListener());
		btnArmor.setActionCommand("armor");
		btnArmor.setText("Armor");
		btnArmor.addActionListener(new BtnActionListener());
		btnResource.addActionListener(new BtnActionListener());
		btnWeapon.addActionListener(new BtnActionListener());
	}
	
	private class BtnActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (form != null) {
				main.remove(form);
			}
			
			String command = e.getActionCommand();
			
			if (command.equals("mobs")) {
				if (formsCache.get(command) == null)
					formsCache.put(command, new FormMobs());
			} else if (command.equals("armor")) {
				if (formsCache.get(command) == null)
					formsCache.put(command, new FormItems());
			}
			
			form = formsCache.get(command);
			main.add(form, new CC().dockNorth().grow());
			main.invalidate();
			main.validate();
			main.update(main.getGraphics());
		}
	}

}
